import logging
import re
import toml
import numpy

from coin.exchange.base.kr_rest.py_product import PyProduct
from coin.strategy.accounting.fee import (
    to_list,
    get_matching_dict,
    relative_norm
)

multiplier_info_legacy = toml.load("data/coin2/order/multiplier_info.toml")


def get_multiplier_legacy_use_hardcode(product, as_of_date=None):
  assert isinstance(product, PyProduct), type(product)
  multiplier_info_product = get_matching_dict(
      multiplier_info_legacy,
      f"{product.market_name}.{product.exchange_name}",
      relative_norm(product) if product else "",
      as_of_date=as_of_date)
  base = product.base.currency
  if len(multiplier_info_product) == 0:
    return 1
  else:
    if base not in multiplier_info_product:
      return multiplier_info_product["default"]
    else:
      return multiplier_info_product[base]


def get_multiplier(product, as_of_date=None):
  assert isinstance(product, PyProduct), type(product)
  try:
    holder = product.product_holder
  except Exception:
    logging.info(f"Can't Get Product Holder : %s.%s.%s" % (
        product.market_name, product.exchange_name, product.symbol))
    return get_multiplier_legacy_use_hardcode(product, as_of_date)
  pi = product.product_holder.product_info
  ret = pi.contract_value
  if ret is None or numpy.isnan(ret):
    if product.exchange_name == 'Bitmex':
      return get_multiplier_legacy_use_hardcode(product, as_of_date)
    else:
      return None
  return ret
